/**
 * name:http服务
 * describe:对http请求做统一处理
 */
import {Injectable} from '@angular/core';
import {User} from '../../models/user';
import {catchError, tap} from 'rxjs/operators';
import {Observable, of} from 'rxjs';
import {HttpClient, HttpHeaders} from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'text/plain'})
};
@Injectable()
export class HttpUtilService {

  constructor(private http: HttpClient) {
  }
  createAuthorizationHeader(headers: HttpHeaders) {
    // headers.append('Authorization', 'Basic ' +
    //   btoa('username:password'));
  }
  /**
   * 统一发送请求
   * @param params
   * @returns {Promise<{success: boolean, msg: string}>|Promise<R>}
   */
  public request(params: any): any {
    // POST请求（参数、返回值类型都是任意类型）
    if (params['method'] === 'post' || params['method'] === 'POST') {
      return this.post(params['url'], params['data']);
    } else { // 其他请求
      return this.get(params['url'], params['data']);
    }
  }
  get2(url) {
    let headers = new HttpHeaders();
    this.createAuthorizationHeader(headers);
    httpOptions.headers = headers;
    return this.http.get(url, {
      headers: headers
    });
  }
  /**
   * get请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  public get(url: string, params: any): any {
    return this.http.get<any>(url, httpOptions).pipe(
      tap((res: any) => this.log(`login`)),
      catchError(this.handleError<any>('login'))
    );
  }

  /**
   * post请求
   * @param url 接口地址
   * @param params 参数
   * @returns {Promise<R>|Promise<U>}
   */
  // this.httpClient.get(url, {'withCredentials': true, responseType: 'text'} )
  public post(url: string, params: any) {
    let headers = new HttpHeaders();
    this.createAuthorizationHeader(headers);
    httpOptions.headers = headers;

    return this.http.post<any>(url, params, httpOptions).pipe(
      tap((res: any) => this.log(`login`)),
      catchError(this.handleError<any>('login'))
    );
    // return this.http.post(url, params)
    //   .toPromise()
    //   .then(this.handleSuccess)
    //   .catch(res => this.handleError(res));
  }

  /**
   * Handle Http operation that failed.
   * Let the app continue.
   * @param operation - name of the operation that failed
   * @param result - optional value to return as the observable result
   */
  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      this.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }

  /** Log a HeroService message with the MessageService */
  private log(message: string) {
    console.log(message);
    // this.messageService.add('HeroService: ' + message);
  }
}
